#!/usr/bin/env bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 默认配置
APP_PORT=":8111"
APP_DEBUG="true"
DB_PATH="data.db"
JWT_SECRET=""

if [[ -f ".env" ]]; then
  set -o allexport
  source ".env"
  set +o allexport
fi

usage() {
  echo "Usage: $0 [--port <port>] [--debug <true|false>] [--db <db_path>] [--jwt-secret <secret>]"
  echo
  echo "Examples:"
  echo "  $0 --port :8111 --debug true --db data.db --jwt-secret mysecret"
  exit 1
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --port)
      APP_PORT="$2"
      shift 2
      ;;
    --debug)
      APP_DEBUG="$2"
      shift 2
      ;;
    --db|--db-path)
      DB_PATH="$2"
      shift 2
      ;;
    --jwt-secret)
      JWT_SECRET="$2"
      shift 2
      ;;
    -h|--help)
      usage
      ;;
    *)
      echo "Unknown option: $1"
      usage
      ;;
  esac
done

if [[ -z "$JWT_SECRET" ]]; then
  echo "Warning: JWT secret not specified, using value from database or default config."
fi

echo "Building ob-share-server..."
go build -o ob-share-server main.go

echo "Starting ob-share-server on port ${APP_PORT} (debug=${APP_DEBUG}, db=${DB_PATH})..."
APP_PORT="$APP_PORT" \
APP_DEBUG="$APP_DEBUG" \
DB_PATH="$DB_PATH" \
JWT_SECRET="$JWT_SECRET" \
./ob-share-server
